﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using WHW_NetUtility;
using MotionControl;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace MainFrame
{
    public partial class frm_MainFrame : Form
    {

        //窗口
        FormDisplay frmDisplay;//数据显示
        FormType frmTypedata;//型号数据
        frm_Main frmAxisConfig;//运动设置
        frm_IOMotionCard frmIOcheck;//IO监控
        //FormCalibration frmCalib;//系统标定
        FormUserManage frmUserM;//用户管理
        FormCommunication frmComm;//通讯设置
        FormAlarm frmAlarm;//警告弹出窗口
        FormDeviceError frmError;//错误弹出窗口

        FormLogin myLogin;//登陆窗口

        //线程
        Thread formInfoDisplay_T;//界面信息显示
        Thread warningErrorTips_T;//警告弹窗和错误弹窗监控
        Thread autoRun_T;//自动运行线程
        Thread getInput_T;//获取通用输入信号
        Thread alarmLamp_T;//收放料缺料、满料报警提示
        private Thread setGreenLight_T;//绿灯闪烁

        //全局时间
        Stopwatch totalTimeSW = new Stopwatch();//软件开启到现在的时间
        Stopwatch runTimeSW = new Stopwatch();//自动运动的时间
        Stopwatch LastTimeSW = new Stopwatch();//上次运行的时间

        long lastTimeCT = 0;//上次运动时间
        CardMotion ioMainCard=null;

        ManualResetEvent autoMRE = new ManualResetEvent(false);

        public const double paperPerDistance = 24.086;//拉砂纸电机的速度 24.086mm/s

        Stopwatch waitLaminteSW = new Stopwatch();

        int NoSensorTimes = 0;

        int pullTempCount = 0;//拉料临时计数，用于打印报警日志
        int takeTempCount = 0;//撕膜临时计数，用于打印报警日志
        int takeTempCount_BackMany = 0;
        int onlyPullTimes = 1;//排空次数
        //int takeTempCount_BackMore = 0;

        private string saveFilePath = Environment.CurrentDirectory + "\\" + "statisticsInfo.sta";//设置数量保存路径
        private Stopwatch axisSW=new Stopwatch();

        public frm_MainFrame()
        {
            InitializeComponent();
            loadTips.loadTipsInLogin("加载主窗体");
        }

        private void frm_MainFrame_Load(object sender, EventArgs e)
        {
            try
            {
                int hegihtView = Screen.PrimaryScreen.Bounds.Height;
                int hegihtWork = Screen.PrimaryScreen.WorkingArea.Height;
                MessageDisplay("程序启动");
                loadTips.loadTipsInLogin("加载主窗体");
                //uint m = Convert.ToUInt16((Math.Ceiling(19.678)).ToString());
                //MessageDisplay(m.ToString());
                displalyInfo.displayInfoMain = MessageDisplay;//关联信息提示全局变量
                //displalyInfo.displayErrorMain = MessageErrorDisplay;//异常信息显示
                MotionControl.GlobalVariable.MessageDisplay = MessageDisplay;//不同工程间的信息提示
                changeUser.changeUserMain += UserLogin;
                //displalyImage.displayImage_M=ImageDisplay_M;//关联测量窗口图像全局显示
                //displalyImage.displayImage_F = ImageDisplay_Fweld;//关联前焊接窗口图像全局显示
                //displalyImage.displayImage_L = ImageDisplay_Lweld;//关联后焊接窗口图像全局显示
                totalTimeSW.Start();//全局计时开始
                GlobalVar.isExit = false;

                #region 用户身份
                UserLogin();
                #endregion

                #region 窗口设置
                loadTips.loadTipsInLogin("加载数据显示窗体");

                //窗口设置--类型数据
                loadTips.loadTipsInLogin("加载类型数据窗体");
                if (frmTypedata == null || frmTypedata.IsDisposed)
                {
                    frmTypedata = new FormType();
                    frmTypedata.TopLevel = false;
                    frmTypedata.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmTypedata);
                    frmTypedata.StartPosition = FormStartPosition.CenterParent;
                }
                //窗口设置--运动设置
                loadTips.loadTipsInLogin("加载运动设置窗体");
                if (frmAxisConfig == null || frmAxisConfig.IsDisposed)
                {
                    frmAxisConfig = new frm_Main();
                    frmAxisConfig.TopLevel = false;
                    frmAxisConfig.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmAxisConfig);
                    frmAxisConfig.StartPosition = FormStartPosition.CenterParent;
                    //frmAxisConfig.Show();
                }

                if (GlobalVariable.ListCard.Count != 0)
                {
                    ioMainCard = (CardMotion)GlobalVariable.ListCard[0];
                }

                //窗口设置--IOcheck
                loadTips.loadTipsInLogin("加载IOCheck窗体");
                if (frmIOcheck == null || frmIOcheck.IsDisposed)
                {
                    frmIOcheck = new frm_IOMotionCard(ref ioMainCard);
                    frmIOcheck.TopLevel = false;
                    frmIOcheck.FormBorderStyle = FormBorderStyle.None;
                    pl_main.Controls.Add(frmIOcheck);
                    frmIOcheck.StartPosition = FormStartPosition.CenterParent;
                }

                //窗口设置--系统标定
                //if (frmCalib == null || frmCalib.IsDisposed)
                //{
                //    frmCalib = new FormCalibration();
                //    frmCalib.TopLevel = false;
                //    frmCalib.FormBorderStyle = FormBorderStyle.None;
                //    pl_main.Controls.Add(frmCalib);
                //    frmCalib.StartPosition = FormStartPosition.CenterParent;
                //}
                //窗口设置--通讯设置
                loadTips.loadTipsInLogin("加载通讯窗体");
                if (frmComm == null || frmComm.IsDisposed)
                {
                    frmComm = new FormCommunication();
                    frmComm.TopLevel = false;
                    frmComm.FormBorderStyle = FormBorderStyle.None;//隐藏边框
                    pl_main.Controls.Add(frmComm);
                }
                //窗口设置--用户管理
                loadTips.loadTipsInLogin("加载用户管理窗体");
                if (frmUserM == null || frmUserM.IsDisposed)
                {
                    frmUserM = new FormUserManage();
                    frmUserM.TopLevel = false;
                    frmUserM.FormBorderStyle = FormBorderStyle.None;//隐藏边框
                    pl_main.Controls.Add(frmUserM);
                }

                #endregion
                loadTips.loadTipsInLogin("弹窗初始化");
                #region 弹窗条件初始化
                //弹窗条件初始化
                for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                {
                    GlobalVar.errorTips[i] = new warningErrorInfo();
                }
                for (int i = 0; i < GlobalVar.warningTips.Length; i++)
                {
                    GlobalVar.warningTips[i] = new warningErrorInfo();
                }
                #endregion

                #region 窗口切换
                showHideWin((int)winIndex.motion);
                //Thread.Sleep(20);
                //showHideWin((int)winIndex.calibation);
                //Thread.Sleep(20);
                //showHideWin((int)winIndex.DataDisplay);
                Thread.Sleep(20);
                showHideWin((int)winIndex.type);
                #endregion
                #region 控制卡检测
                if (GlobalVariable.ListCard.Count != 0)
                {
                    ioMainCard = (CardMotion)GlobalVariable.ListCard[0];
                    GlobalVar.isHardStart = true;
                }
                else
                {
                    displalyInfo.displayInfoMain("没有找到控制卡，ListCard=0");
                    GlobalVar.isHardStart = false;
                }
                #endregion

                #region IOcheck窗口设定
                //窗口设置--IOcheck
                frmIOcheck = new frm_IOMotionCard(ref ioMainCard);
                frmIOcheck.TopLevel = false;
                frmIOcheck.FormBorderStyle = FormBorderStyle.None;
                pl_main.Controls.Add(frmIOcheck);
                frmIOcheck.StartPosition = FormStartPosition.CenterParent;
                #endregion

                #region 线程启动
                //启动界面更新线程
                formInfoDisplay_T = new Thread(formInfoDisplay);//界面更新线程
                formInfoDisplay_T.IsBackground = true;//后台线程
                formInfoDisplay_T.Name = "formInfoDisplay";
                formInfoDisplay_T.Start();
                                          
                warningErrorTips_T = new Thread(warningErrorTips);//启动警告及错误提示线程
                warningErrorTips_T.IsBackground = true;
                warningErrorTips_T.Name = "warningErrorTips";
                warningErrorTips_T.Start();

                //autoRun_T = new Thread(()=>AutoRun());//自动运行线程
                //autoRun_T.IsBackground = true;
                //autoRun_T.Name = "AutoRun";
                //autoRun_T.Start();

                getInput_T = new Thread(GetInput);//获取输入
                getInput_T.IsBackground = true;
                getInput_T.Name = "GetInput";
                getInput_T.Start();

                setGreenLight_T = new Thread(setGreenLight);//绿灯闪烁
                setGreenLight_T.IsBackground = true;
                setGreenLight_T.Name = "setGreenLight";
                setGreenLight_T.Start();

                alarmLamp_T = new Thread(AlarmLamp);//黄灯报警
                alarmLamp_T.IsBackground = true;
                alarmLamp_T.Name = "AlarmLamp";
                alarmLamp_T.Start();
                #endregion
                DeserializeFile();
                CSVconfig();//文件保存配置
                loadTips.loadTipsInLogin("启动复原");
                #region 复原
                //GoHomeInMain();
                #endregion
                

            }
            catch (System.Exception ex)
            {
                MessageDisplay("程序启动异常：" + ex.Message);
            }
            
        }


        public void UserLogin()
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => {

                    if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.operatorStaff)
                    {
                        btn_type.Enabled = true;
                        btn_userManage.Enabled = false;
                        btn_MotionControl.Enabled = false;
                        btn_IOcheck.Enabled = false;
                        btn_communication.Enabled = false;
                        btn_step.Enabled = false;
                        tssl_permissionAndUserName_status.Text = $"操作员,{MotionControl.GlobalVariable.OperName}";
                        //showHideWin((int)(winIndex.type));
                        MessageDisplay("以操作员身份登陆");
                    }
                    else if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.technician)
                    {
                        btn_type.Enabled = true;
                        btn_userManage.Enabled = false;
                        btn_MotionControl.Enabled = false;
                        btn_IOcheck.Enabled = true;
                        btn_communication.Enabled = true;
                        btn_step.Enabled = true;
                        tssl_permissionAndUserName_status.Text = $"技术员,{MotionControl.GlobalVariable.OperName}";
                        //showHideWin((int)(winIndex.type));
                        MessageDisplay("以技术员身份登陆");
                    }
                    else
                    {
                        btn_type.Enabled = true;
                        btn_userManage.Enabled = true;
                        btn_MotionControl.Enabled = true;
                        btn_IOcheck.Enabled = true;
                        btn_communication.Enabled = true;
                        btn_step.Enabled = true;
                        tssl_permissionAndUserName_status.Text = $"管理员,{MotionControl.GlobalVariable.OperName}";
                        MessageDisplay("以管理员身份登陆");
                    }
                }));
            }
            else
            {
                if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.operatorStaff)
                {
                    btn_type.Enabled = true;
                    btn_userManage.Enabled = false;
                    btn_MotionControl.Enabled = false;
                    btn_IOcheck.Enabled = false;
                    btn_communication.Enabled = false;
                    btn_step.Enabled = false;
                    tssl_permissionAndUserName_status.Text = $"操作员,{MotionControl.GlobalVariable.OperName}";
                    //showHideWin((int)(winIndex.type));
                    MessageDisplay("以操作员身份登陆");
                }
                else if (MotionControl.GlobalVariable.OperLevel == (int)MotionControl.operLevel.technician)
                {
                    btn_type.Enabled = true;
                    btn_userManage.Enabled = false;
                    btn_MotionControl.Enabled = false;
                    btn_IOcheck.Enabled = true;
                    btn_communication.Enabled = true;
                    btn_step.Enabled = true;
                    tssl_permissionAndUserName_status.Text = $"技术员,{MotionControl.GlobalVariable.OperName}";
                    //showHideWin((int)(winIndex.type));
                    MessageDisplay("以技术员身份登陆");
                }
                else
                {
                    btn_type.Enabled = true;
                    btn_userManage.Enabled = true;
                    btn_MotionControl.Enabled = true;
                    btn_IOcheck.Enabled = true;
                    btn_communication.Enabled = true;
                    btn_step.Enabled = true;
                    tssl_permissionAndUserName_status.Text = $"管理员,{MotionControl.GlobalVariable.OperName}";
                    MessageDisplay("以管理员身份登陆");
                }
            }
            
        }

        /// <summary>
        /// 在信息框写入提示信息
        /// </summary>
        /// <param name="message"></param>
        public void MessageDisplay(string message)
        {
            try
            {
                if (InvokeRequired)
                {
                    tbx_displayMessage.Invoke(new MethodInvoker(() =>
                    {
                        DateTime NowTime = DateTime.Now;
                        tbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                        tbx_displayMessage.ScrollToCaret();
                    }));
                }
                else
                {
                    DateTime NowTime = DateTime.Now;
                    tbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                    tbx_displayMessage.ScrollToCaret();
                }

                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }
            
        }

        /// <summary>
        /// 在信息框写入提示信息
        /// </summary>
        /// <param name="message"></param>
        public void MessageDisplay(string message,string english="")
        {
            try
            {
                if (InvokeRequired)
                {
                    tbx_displayMessage.Invoke(new MethodInvoker(() =>
                    {
                        DateTime NowTime = DateTime.Now;
                        tbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                        tbx_displayMessage.ScrollToCaret();
                    }));
                }
                else
                {
                    DateTime NowTime = DateTime.Now;
                    tbx_displayMessage.AppendText(NowTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + "  " + message + Environment.NewLine);
                    tbx_displayMessage.ScrollToCaret();
                }

                Log4Helper.WriteLog("界面信息", message);
            }
            catch (Exception)
            {
            }

        }

        public void CSVconfig()
        {
            StreamWriter csvStreamWriter;
            string path_Save = Environment.CurrentDirectory + "\\CSV";
            if (!Directory.Exists(path_Save))
            {
                Directory.CreateDirectory(path_Save);
            }
            string saveDate = DateTime.Now.ToString("yyyy_MM_dd");
            GlobalVar.CSVpath = path_Save + "\\" + saveDate + ".CSV";
            if (!File.Exists(GlobalVar.CSVpath))
            {
                csvStreamWriter = new StreamWriter(GlobalVar.CSVpath, true, Encoding.Unicode);
                csvStreamWriter.Write("序号\t贴合状态\t贴合用时\t写入时间\r\n");
                csvStreamWriter.Flush();
                csvStreamWriter.Close();
            }
        }
        /// <summary>
        /// 显示隐藏窗口
        /// </summary>
        /// <param name="winNumber">窗口对应的ID号</param>
        public void showHideWin(int winNumber)
        {
            switch (winNumber)
            {
                case (int)winIndex.DataDisplay:
                    //frmDisplay.Show();
                    frmTypedata.Hide();                    
                    frmAxisConfig.Hide();
                    frmIOcheck.Hide();
                    //frmCalib.Hide();
                    frmComm.Hide();
                    frmUserM.Hide();
                    break;
                case (int)winIndex.type:
                    //frmDisplay.Hide();
                    frmTypedata.Show();
                    frmAxisConfig.Hide();
                    frmIOcheck.Hide();
                    //frmCalib.Hide();
                    frmComm.Hide();
                    frmUserM.Hide();
                    break;
                case (int)winIndex.motion:
                    //frmDisplay.Hide();
                    frmTypedata.Hide();
                    frmAxisConfig.Show();
                    frmIOcheck.Hide();
                    //frmCalib.Hide();
                    frmComm.Hide();
                    frmUserM.Hide();
                    break;
                case (int)winIndex.IOcheck:
                    //frmDisplay.Hide();
                    frmTypedata.Hide();
                    frmAxisConfig.Hide();
                    frmIOcheck.Show();
                    //frmCalib.Hide();
                    frmComm.Hide();
                    frmUserM.Hide();
                    break;
                case (int) winIndex.calibation:
                    //frmDisplay.Hide();
                    frmTypedata.Hide();
                    frmAxisConfig.Hide();
                    frmIOcheck.Hide();
                    //frmCalib.Show();
                    frmComm.Hide();
                    frmUserM.Hide();
                    break;
                case (int)winIndex.communication:
                    //frmDisplay.Hide();
                    frmTypedata.Hide();
                    frmAxisConfig.Hide();
                    frmIOcheck.Hide();
                    //frmCalib.Hide();
                    frmComm.Show();
                    frmUserM.Hide();
                    break;
                case (int)winIndex.userManage:
                    //frmDisplay.Hide();
                    frmTypedata.Hide();
                    frmAxisConfig.Hide();
                    frmIOcheck.Hide();
                    //frmCalib.Hide();
                    frmComm.Hide();
                    frmUserM.Show();
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 界面更新函数
        /// </summary>
        private void formInfoDisplay()
        {
            try
            {
                Stopwatch tempSw = new Stopwatch();
                while (true)
                {
                    tempSw.Restart();
                    Thread.Sleep(500);//0.5秒刷新一下界面

                    #region 界面设置
                    this.Invoke(new Action(() =>
                    {
                        if (GlobalVar.isAutoRun)
                        {
                            tssl_machineStatus_status.Text = "运行中";
                            tssl_machineStatus_status.BackColor = System.Drawing.Color.Green;
                            btn_Home.Enabled = false;//自动运行时，不能回原
                            btn_start.Enabled = false;
                            btn_step.Enabled = false;//自动运动时，不能单步
                        }
                        else
                        {
                            tssl_machineStatus_status.Text = "未开始";
                            tssl_machineStatus_status.BackColor = System.Drawing.Color.Yellow;
                            btn_Home.Enabled = true;
                            btn_start.Enabled = true;
                            btn_step.Enabled = false;
                        }
                   
                        tssl_cardConnect_status.Text = MotionControl.GlobalVariable.isCardStart[0]? "已连接": "未连接";
                        tssl_cardConnect_status.BackColor = MotionControl.GlobalVariable.isCardStart[0] ? Color.Green:Color.Red;

                    }));
                    #endregion

                    if (tempSw.ElapsedMilliseconds>GlobalVar.FormInfoT_time)
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = true;
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "界面信息刷新线程出错";
                    }
                    else
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = false;
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "";
                    }
                    if (GlobalVar.setupNum==GlobalVar.completeNum)
                    {
                        GlobalVar.warningTips[(int)GlobalVar.warningType.complete].haveInfo = true;
                    }
                    else
                    {
                        GlobalVar.warningTips[(int)GlobalVar.warningType.complete].haveInfo = false;
                    }
                    if (GlobalVar.isExit)
                    {
                        break;
                    }
                    //MessageDisplay("界面更新线程运动时间是：" + tempSw.ElapsedMilliseconds.ToString());//不加延时，此方法运行时间0-15ms
                }
            }
            catch (System.Exception ex)
            {
                Log4Helper.WriteLog("MainForm", ex);
            }


        }
        /// <summary>
        /// 警告和错误弹出窗口
        /// </summary>
        private void warningErrorTips()
        {
            Stopwatch WETsw = new Stopwatch();
            bool AxisAlarm = false;//轴报警
            //bool AxisMerror = false;//轴跟随误差
            bool AxisNegLimit = false;//轴负限位
            bool AxisPosLimit = false;//轴正限位
            bool AxisHoming = false;//回原中
            string currentAxis = "0轴";//当前轴
            string tempError = "";//轴报警内容
            //bool popupWin = false;//弹窗弹出标识
            bool axisAllError = false;
            stuAxisSts asm=new stuAxisSts();
            while (true)
            {
                //在弹窗中清除信息
                WETsw.Restart();
                Thread.Sleep(20);
                for (int i = 0; i < GlobalVar.warningTips.Length; i++)
                {
                    //GlobalVar.warningTips[i].haveInfo = false;
                    GlobalVar.warningTips[i].Info = "";
                }
                //for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                //{
                //    //GlobalVar.errorTips[i].haveInfo = false;
                //    GlobalVar.errorTips[i].Info = "";
                //}
                GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].Info = string.Empty;
                GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = string.Empty;
                axisAllError = false;
                try
                {                    
                    #region axisError
                    for (int i = 0; i < GlobalMotion.mainCard.AxisList.Count; i++)
                    {
                        currentAxis = i.ToString() + " 轴";
                        AxisAlarm = false;//轴报警
                        //AxisMerror = false;//轴跟随误差
                        AxisNegLimit = false;//轴负限位
                        AxisPosLimit = false;//轴正限位

                        AxisAlarm = GlobalMotion.mainCard.AxisList[i].m_AxisSts.Alarm;
                        ////AxisMerror = GlobalMotion.mainCard.AxisList[i].m_AxisSts.Merror;
                        AxisNegLimit = GlobalMotion.mainCard.AxisList[i].m_AxisSts.NegLimit;
                        if (i==2)
                        {
                            AxisPosLimit = GlobalMotion.mainCard.AxisList[i].m_AxisSts.PosLimit&&GlobalVar.isMagneticRising;
                        }
                        else
                        {
                            AxisPosLimit = GlobalMotion.mainCard.AxisList[i].m_AxisSts.PosLimit;
                        }
                        AxisHoming = GlobalMotion.mainCard.AxisList[i].m_AxisSts.HomingFlag;

                        tempError = "";
                        if (AxisAlarm || ((AxisNegLimit || AxisPosLimit)&&(!AxisHoming)))
                        {
                            //AxisTemp = true;
                            //GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].haveInfo = true;
                            //Thread.Sleep(10);
                            axisAllError = axisAllError | true;
                            if (AxisAlarm)
                            {
                                tempError += "伺服报警 ";
                            }
                            //if (AxisMerror)
                            //{
                            //    tempError += "伺服误差超限 ";
                            //}
                            if (AxisNegLimit)
                            {
                                tempError += "触碰负限位 ";
                            }
                            if (AxisPosLimit)
                            {
                                tempError += "触碰正限位 ";
                            }
                            GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].Info += currentAxis + tempError + Environment.NewLine;
                        }
                        else
                        {
                            axisAllError = axisAllError | false;
                        }
                    }
                    if (axisAllError)
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].haveInfo = true;
                        //GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].Info += currentAxis + tempError + Environment.NewLine;
                    }
                    else
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].haveInfo = false;
                        GlobalVar.errorTips[(int)GlobalVar.errorType.axisError].Info = "";
                    }
                    #endregion

                    #region threadError     add according to your requirement
                    if (!formInfoDisplay_T.IsAlive|| !warningErrorTips_T.IsAlive)
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = true;
                        if (!formInfoDisplay_T.IsAlive)
                        {

                            GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "界面更新任务（线程）没有正常运行";
                        }
                        if (!warningErrorTips_T.IsAlive)
                        {
                            GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "警告及错误检测任务（线程）没有正常运行";
                        }
                        if (!formInfoDisplay_T.IsAlive&& !warningErrorTips_T.IsAlive)
                        {
                            GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "界面更新任务（线程）没有正常运行"+Environment.NewLine+
                             "警告及错误检测任务（线程）没有正常运行";
                        }
                    }
                    else
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = false;
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "";
                    }
                    
                    #endregion

                    #region popup error windows
                    for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                    {
                        if (GlobalVar.errorTips[i].haveInfo)
                        {
                            try
                            {
                                if (frmError == null || frmError.IsDisposed)
                                {
                                    frmError = new FormDeviceError();
                                    frmError.TopMost = true;//topMost为true,窗口保持在最前端;topLevel为true，窗口不能嵌套在其它窗口内
                                    this.Invoke(new MethodInvoker(() => frmError.Show()));//直接调用会报错
                                }
                                //如果用activate的话，由于刷新频率比较快，窗口会出现类似于模态对话框的效果，导致其它界面无法正常操作
                                //activate在窗口切换时被触发（使窗口获得焦点）
                                //else{ this.Invoke(new MethodInvoker(() => frmDevError.Activate()));//直接调用会报错 }
                            }
                            catch (Exception ex)
                            {
                                MessageDisplay("弹出错误窗体出错"+Environment.NewLine+ex.Message);
                                Log4Helper.WriteLog("mainForm", ex);
                            }
                            break;
                        }
                    }
                    #endregion

                    #region popup warning windows
                    for (int i = 0; i < GlobalVar.warningTips.Length; i++)
                    {
                        if (GlobalVar.warningTips[i].haveInfo)
                        {
                            try
                            {
                                if (frmAlarm == null || frmAlarm.IsDisposed)
                                {
                                    frmAlarm = new FormAlarm();
                                    frmAlarm.TopMost = true;//topMost为true,窗口保持在最前端;topLevel为true，窗口不能嵌套在其它窗口内
                                    this.Invoke(new MethodInvoker(() => frmAlarm.Show()));//直接调用会报错
                                }
                                //如果用activate的话，由于刷新频率比较快，窗口会出现类似于模态对话框的效果，导致其它界面无法正常操作
                                //activate在窗口切换时被触发（使窗口获得焦点）
                                //else{ this.Invoke(new MethodInvoker(() => frmDevError.Activate()));//直接调用会报错 }
                            }
                            catch (Exception ex)
                            {
                                MessageDisplay("弹出警告窗体出错" + Environment.NewLine + ex.Message);
                                Log4Helper.WriteLog("mainForm", ex);
                            }
                            break;
                        }
                    }
                    #endregion

                    if (WETsw.ElapsedMilliseconds>GlobalVar.FormInfoT_time)
                    {
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = true;
                        GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "弹窗任务超时";
                    }
                    //else
                    //{
                    //    GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].haveInfo = false;
                    //    GlobalVar.errorTips[(int)GlobalVar.errorType.threadError].Info = "";
                    //}
                    //MessageDisplay("弹窗任务耗时：" + WETsw.ElapsedMilliseconds.ToString());
                    if (GlobalVar.isExit)
                    {
                        break;
                    }
                }
                catch (System.Exception ex)
                {
                    //Log4Helper.WriteLog("mainForm", ex);
                    MessageDisplay("获取 需要人工干预及错误窗口异常：" + ex.Message);
                    break;//待确认是否需要报错
                }          
            }
        }

        private void setGreenLight()
        {
            while (true)
            {
                Thread.Sleep(100);           
                if (!GlobalVar.isAutoRun&&!GlobalVar.isEstop&&!GlobalVar.isAlarmPopup)
                {
                    //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 0);//绿灯亮
                    //Thread.Sleep(1000);
                    //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 1);//绿灯灭
                    //Thread.Sleep(1000);
                    continue;
                }
                if (GlobalVar.isAutoRun)
                {
                    //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 0);//绿灯亮
                }
            }
        }
        private void GetInput()
        {
            //while ( true)
            //{
            //    try
            //    {
            //        Thread.Sleep(10);
            //        bool status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 0);
            //        if (status)
            //        {
            //            if (!GlobalVar.isAutoRun)
            //            {
            //                Task.Factory.StartNew(Operate_Start);
            //            }
            //            else
            //            {
            //                if (GlobalVar.isStep)
            //                {
            //                    Task.Factory.StartNew(Operate_Start);
            //                }
            //            }
            //        }
            //        status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 1);
            //        if (status && GlobalVar.isAutoRun)
            //        {
            //            Operate_Stop();
            //        }
            //        status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 2);
            //        if (status&&(!GlobalVar.isStepNext))
            //        {
            //            //displalyInfo.displayInfoMain("单步执行");
            //            Operate_Step();
                        
            //        }

            //        //底膜放料缺料
            //        status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 5);
            //        if (!status)
            //        {
            //            Task.Factory.StartNew(() =>
            //            {

            //                Stopwatch stpw = new Stopwatch();
            //                stpw.Restart();
            //                while (true)
            //                {
            //                    Thread.Sleep(10);
            //                    status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 5);
            //                    if (status)
            //                    {
            //                        break;
            //                    }
            //                    if (stpw.ElapsedMilliseconds > 3000)
            //                    {
            //                        GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].haveInfo = true;
            //                        GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].Info = "底膜缺料，请补料！";
            //                        break;
            //                    }
            //                }
            //            });
            //        }
         

            //        //放料底膜少料
            //        status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 13);
            //        if (!status)
            //        {
            //            if (GlobalVar.currentCirclePullNumber>GlobalVar.typedata_g.PullFilmSensorTimes)
            //            {
            //                GlobalVar.isHaveAlarm = true;//缺料报警，只报警，不停机
            //                if (pullTempCount!=GlobalVar.currentCirclePullNumber)
            //                {
            //                    MessageDisplay("放料底膜少料报警！！！");
            //                }
            //                pullTempCount = GlobalVar.currentCirclePullNumber;
            //            }
            //            //GlobalVar.warningTips[(int)GlobalVar.warningType.changeSandPaper].haveInfo = true;
            //            //GlobalVar.warningTips[(int)GlobalVar.warningType.changeSandPaper].Info = "请换砂纸！";
            //        }
            //        else
            //        {
            //            Interlocked.Exchange(ref GlobalVar.currentCirclePullNumber, 0);
            //            GlobalVar.isHaveAlarm = false;
            //        }
                   
            //        //满料停止
            //        if (GlobalVar.checkIsLotsOfAM)
            //        {
            //            status = false;
            //            status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 12);
            //            if (status)
            //            {
            //                GlobalVar.isLotsOfAM = true;
            //            }
            //            else
            //            {
            //                GlobalVar.isLotsOfAM = false;
            //            }
            //        }
            //        else
            //        {
            //            GlobalVar.isLotsOfAM = false;
            //        }
            //        //门开关
            //        if (GlobalVar.isDoorEnable)
            //        {
            //            status = true;
            //            status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 14);
            //            if (!status)
            //            {
            //                GlobalVar.isDoorOpen = true;
            //                Interlocked.Exchange(ref GlobalVar.doorCount, 0);
            //                if (GlobalVar.isAutoRun)
            //                {
            //                    GlobalVar.isPause = true;
            //                    GlobalVar.isAutoRun = false;
            //                    //GlobalVar.isStep = false;
            //                    //GlobalVar.isStepNext = false;
            //                }
            //            }
            //            else
            //            {
            //                if (GlobalVar.isPause&&!GlobalVar.isAutoRun&&GlobalVar.doorCount==0)
            //                {
            //                    Task.Factory.StartNew(Operate_Start);
            //                }
            //                Interlocked.Increment(ref GlobalVar.doorCount);
            //                if (GlobalVar.doorCount>1000)
            //                {
            //                    Interlocked.Exchange(ref GlobalVar.doorCount,1000);
            //                }
            //                GlobalVar.isDoorOpen = false;
            //            }
            //        }
            //        else
            //        {
            //            //if (GlobalVar.isPause && !GlobalVar.isAutoRun)
            //            //{
            //            //    Task.Factory.StartNew(Operate_Start);
            //            //}
            //            GlobalVar.isDoorOpen = false;
            //        }
            //        //紧急停止
            //        status = false;
            //        status = MotionControl.GlobalVariable.HOperation.GetBitInput(GlobalMotion.mainCard.m_CardID, 15);
            //        if (!status)
            //        {
            //            GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo = true;
            //            GlobalVar.warningTips[(int)GlobalVar.errorType.softEstop].Info = "紧急停止！";
            //        }
            //        else
            //        {
            //            if (!GlobalVar.isEstop)
            //            {
            //                GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo = false;
            //                GlobalVar.warningTips[(int)GlobalVar.errorType.softEstop].Info = "";
            //            }
                        
            //        }
            //        if (GlobalVar.isExit)
            //        {
            //            break;
            //        }
            //    }
            //    catch (Exception)
            //    {

            //    }
                
            //}
        }
        private void btn_MotionControl_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入运动模块");
            showHideWin((int)(winIndex.motion));
        }

        private void btn_userLogin_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入用户管理模块");
            showHideWin((int)winIndex.userManage);            
        }

        private void frm_MainFrame_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                GlobalVar.isExit = true;
                /*lobalMotion.setAllOut();*/

                GlobalMotion.mainCard.StopAllAxis();

                SerializeFile();
                frmAxisConfig.Close();
                Application.Exit();
            }
            catch (Exception)
            {

            }
          
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
             DialogResult exit= MessageBox.Show("确定退出系统吗？","退出系统",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (exit==DialogResult.Yes)
            {
                GlobalMotion.mainCard.StopAllAxis();
                this.Close();
            }
        }

        /// <summary>
        /// 窗口索引
        /// </summary>
        private enum winIndex
        {
            DataDisplay=0,
            type,
            motion,
            IOcheck,
            calibation,
            communication,
            userManage
        }

        private void btn_communication_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入通讯管理模块");
            showHideWin((int)winIndex.communication);
        }

        private void btn_clearInfo_Click(object sender, EventArgs e)
        {
            tbx_displayMessage.Text = "";
        }

        private void btn_dataDisplay_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入数据显示模块");
            showHideWin((int)(winIndex.DataDisplay));
        }

        private void btn_step_Click(object sender, EventArgs e)
        {
            //MessageDisplay("单步运行");
            GlobalVar.isStep = true;
            //GlobalVar.isAutoRun = false;
            GlobalVar.isStepNext = true;
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            if (!GlobalVar.typeDataOK)
            {
                MessageDisplay("请先载入配置文档再操作！！！");
                return;
            }
            btn_start.Enabled = false;
            btn_Home.Enabled = false;
            FormPullTips frmpull = new FormPullTips();
            frmpull.TopMost = true;
            frmpull.Show();
            GlobalVar.isStartPullYes = false;
            GlobalVar.isStartPullNo = false;
            Stopwatch sw = new Stopwatch();
            sw.Restart();
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    Thread.Sleep(50);
                    if (GlobalVar.isStartPullNo|| GlobalVar.isStartPullYes)
                    {
                        break;
                    }
        
                }
                Operate_Start();
            });
      
           
            //GlobalVar.isExit = false;
        }

        private void Operate_Start()
        {
            

            //MessageDisplay("自动运行线程是否在运行：  ["+autoRun_T.IsAlive.ToString()+"]----自动运行线程状态：["+autoRun_T.ThreadState+"]");
            MessageDisplay("自动运行当前运动流程号：  [" + GlobalVar.stepNo.ToString() + "]");
            //Interlocked.Exchange(ref GlobalVar.currentCirclePullNumber, 0);//撕膜放料检测传感器计数置0

            GlobalMotion.ToPosition_Get();
            GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].haveInfo = false;
            GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].Info = string.Empty;

            Interlocked.Exchange(ref GlobalVar.turnplateNO, 0);
            Interlocked.Exchange(ref GlobalVar.resuckNumber,0);

            if (!GlobalVar.typeDataOK)
            {
                GlobalVar.warningTips[(int)GlobalVar.warningType.noData].haveInfo = true;
                GlobalVar.warningTips[(int)GlobalVar.warningType.noData].Info = "型号数据未准备";
                return;
            }
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)0, 0);//打开光源
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)1, 0);
            //Thread.Sleep(10);
            if (GlobalVar.stepNo==7)
            {
                Interlocked.Exchange(ref GlobalVar.stepNo, 1);
            }
            Interlocked.Exchange(ref NoSensorTimes, 0);
            Thread.Sleep(200);
            runTimeSW.Start();
            GlobalMotion.mainCard.setOut((int)e_light_IO.green, e_out_OnOff.on);
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 0);//绿灯亮

            GlobalVar.isNextCircle = true;

            if (!GlobalVar.isPause||GlobalVar.isGiveUp)
            {
                GlobalVar.isPosiveZ = false;
                //if (GlobalVar.isGiveUp) //20190718注释掉
                //{
                //    GlobalVar.frontStationHave = false;//启动后转盘先转一个工位，不管当前工位有没有料
                //}               
                Interlocked.Exchange(ref GlobalVar.stepNo, 4);
                //displalyInfo.displayInfoMain("转盘转。。。。。");
            }
            if (GlobalMotion.mainCard.AxisList[2].m_AxisSts.CurrPosi>5&&GlobalVar.isPause)
            {
                GlobalVar.isPosiveZ = true;
            }
            GlobalVar.isAutoRun = true;
            GlobalVar.isStep = false;
            GlobalVar.isEstop = false;
            GlobalVar.isGiveUp = false;
            GlobalVar.isPause = false;
            GlobalVar.isHome = false;
            GlobalVar.isNeedResuck = false;

            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    btn_start.Enabled = false;
                    btn_Home.Enabled = false;
                    btn_Stop.Enabled = true;
                }));
            }
            else
            {
                btn_start.Enabled = false;
                btn_Home.Enabled = false;
                btn_Stop.Enabled = true;
            }
            waitLaminteSW.Reset();
            MessageDisplay("已启动自动运行");
        }

        /// <summary>
        /// 黄灯报警，只报警不停机
        /// </summary>
        public void AlarmLamp()
        {
            try
            {
                while (true)
                {
                    Thread.Sleep(200);
                    if (GlobalVar.isHaveAlarm)
                    {
                        //MotionControl.GlobalVariable.HOperation.SetOut(0, (ushort)10, 0);//黄灯报警
                        Thread.Sleep(2000);
                        //MotionControl.GlobalVariable.HOperation.SetOut(0, (ushort)10, 1);//取消黄灯报警
                    }
                    if (GlobalVar.isExit)
                    {
                        break;
                    }                
                }
            }
            catch (Exception ex)
            {
                MessageDisplay("提醒报警异常："+ex.Message);
            }
        }
        private void Operate_Stop()
        {
            MessageDisplay("自动运行暂停...");
            runTimeSW.Stop();
            LastTimeSW.Stop();
            
            GlobalVar.isAutoRun = false;
            GlobalVar.isPause = true;
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 1);//绿灯灭
            ControlSetup(true);
            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    btn_start.Enabled = true;
                    btn_Stop.Enabled = false;
                }));
            }
            else
            {
                btn_start.Enabled = true;
                btn_Stop.Enabled = false;
            }
            Task.Factory.StartNew(() => {
                Thread.Sleep(8000);
                GlobalMotion.mainCard.AxisList[7].AxisStop();
            });
        }
        private void Operate_Step()
        {
            MessageDisplay("单步执行");
            GlobalVar.isStep = true;
            //GlobalVar.isAutoRun = false;
            GlobalVar.isStepNext = true;
        }
        private void Operate_GiveUp()
        {
            MessageDisplay("放弃操作");
            runTimeSW.Stop();
            LastTimeSW.Stop();
            //GlobalMotion.mainCard.AxisList[7].AxisStop();
            MotionControl.GlobalVariable.HOperation.AllAxisStop(GlobalMotion.mainCard.m_CardID);
            GlobalVar.isAutoRun = false;
            GlobalVar.isGiveUp = true;
            if (InvokeRequired)
            {
                this.Invoke(new Action(() =>
                {
                    btn_start.Enabled = true;
                    btn_Stop.Enabled = false;
                    btn_Home.Enabled = true;
                }));
            }
            else
            {
                btn_start.Enabled = true;
                btn_Stop.Enabled = false;
                btn_Home.Enabled = true;
            }
            //MotionControl.GlobalVariable.HOperation.SetOut(GlobalMotion.mainCard.m_CardID, (ushort)11, 1);//绿灯灭
            //Interlocked.Exchange(ref GlobalVar.stepNo ,4);//操作步设置为0
        }

        private void Operate_Home()
        {
            ClearErrorStatus();
            Thread.Sleep(30);

            GoHomeInMain();
            GlobalMotion.mainCard.ResetAllIO();
            Interlocked.Exchange(ref GlobalVar.turnplateNO,0);
        }

     

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            Operate_Stop();
            //GlobalVar.isExit = false;
        }

        private void btn_GiveUp_Click(object sender, EventArgs e)
        {
            Operate_GiveUp();
        }
        public void Estop()
        {
            runTimeSW.Stop();
            LastTimeSW.Stop();
            GlobalVar.isAutoRun = false;
            GlobalVar.isStep = false;
            MotionControl.GlobalVariable.HOperation.AllAxisStop(GlobalMotion.mainCard.m_CardID);

            if (GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo)
            {
                GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo = false;
                GlobalVar.isEstop = false;

                GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].haveInfo = false;
                GlobalVar.errorTips[(int)GlobalVar.errorType.needTakeAM].Info = string.Empty;

                GlobalVar.errorTips[(int)GlobalVar.errorType.weldError].haveInfo = false;
                GlobalVar.errorTips[(int)GlobalVar.errorType.weldError].Info = string.Empty;

                MessageDisplay("软件急停取消");
            }
            else
            {
                GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo = true;
                GlobalVar.isEstop = true;

                GlobalVar.isAutoRun = false;
                GlobalVar.isStep = false;
                Interlocked.Exchange(ref GlobalVar.stepNo, 4);

                MessageDisplay("软件急停");
            }
        }
        private void btn_AburptStop_Click(object sender, EventArgs e)
        {

            //GlobalVar.errorTips[(int)GlobalVar.errorType.softEstop].haveInfo = true;

            Estop();
        }

        private void btn_type_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入型号设置模块");
            showHideWin((int)(winIndex.type));
        }

        private void btn_IOcheck_Click(object sender, EventArgs e)
        {
            MessageDisplay("进入IO监控模块");
            showHideWin((int)(winIndex.IOcheck));
        }

        //private void vbx_mainImage_MouseMove(object sender, MouseEventArgs e)
        //{
        //    try
        //    {
        //        if (GlobalImage.MeasureMat == null)
        //        {
        //            return;
        //        }
        //        //vbx_mainImage.Focus();

        //        System.Drawing.Point currentPoint = vbx_mainImage.PointToImage(new System.Drawing.Point(e.X, e.Y));
        //        if (currentPoint.X >= 0 && currentPoint.Y >= 0 && currentPoint.X <= GlobalImage.MeasureMat.Width && currentPoint.Y <= GlobalImage.MeasureMat.Height)
        //        {
        //            string displalyInfo = "";
        //            if (GlobalImage.MeasureMat.Channels() == 3)
        //            {
        //                byte RGB_B = GlobalImage.MeasureMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[0];
        //                byte RGB_G = GlobalImage.MeasureMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[1];
        //                byte RGB_R = GlobalImage.MeasureMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[2];
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + RGB_R.ToString() + "  G:" + RGB_G.ToString() + "  B:" + RGB_B.ToString();
        //            }
        //            else if (GlobalImage.MeasureMat.Channels() == 1)
        //            {
        //                byte pixel = GlobalImage.MeasureMat.At<byte>(currentPoint.Y, currentPoint.X);
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + pixel.ToString() + "  G:" + pixel.ToString() + "  B:" + pixel.ToString();
        //            }
        //            lbl_pixel.Text = displalyInfo;
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        displalyInfo.displayInfoMain("坐标像素信息显示异常："+ex.Message);
        //    }
        //}

        //private void vbx_Fweld_MouseMove(object sender, MouseEventArgs e)
        //{
        //    try
        //    {
        //        if (GlobalImage.FweldMat == null)
        //        {
        //            return;
        //        }
        //        vbx_Fweld.Focus();

        //        System.Drawing.Point currentPoint = vbx_Fweld.PointToImage(new System.Drawing.Point(e.X, e.Y));
        //        if (currentPoint.X >= 0 && currentPoint.Y >= 0 && currentPoint.X <= GlobalImage.FweldMat.Width && currentPoint.Y <= GlobalImage.FweldMat.Height)
        //        {
        //            string displalyInfo = "";
        //            if (GlobalImage.FweldMat.Channels() == 3)
        //            {
        //                byte RGB_B = GlobalImage.FweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[0];
        //                byte RGB_G = GlobalImage.FweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[1];
        //                byte RGB_R = GlobalImage.FweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[2];
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + RGB_R.ToString() + "  G:" + RGB_G.ToString() + "  B:" + RGB_B.ToString();
        //            }
        //            else if (GlobalImage.FweldMat.Channels() == 1)
        //            {
        //                byte pixel = GlobalImage.FweldMat.At<byte>(currentPoint.Y, currentPoint.X);
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + pixel.ToString() + "  G:" + pixel.ToString() + "  B:" + pixel.ToString();
        //            }
        //            lbl_FweldPixel.Text = displalyInfo;
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        displalyInfo.displayInfoMain("前焊接位坐标像素信息显示异常：" + ex.Message);
        //    }
        //}

        //private void vbx_Lweld_MouseMove(object sender, MouseEventArgs e)
        //{
        //    try
        //    {
        //        if (GlobalImage.LweldMat == null)
        //        {
        //            return;
        //        }
        //        vbx_Lweld.Focus();

        //        System.Drawing.Point currentPoint = vbx_Lweld.PointToImage(new System.Drawing.Point(e.X, e.Y));
        //        if (currentPoint.X >= 0 && currentPoint.Y >= 0 && currentPoint.X <= GlobalImage.LweldMat.Width && currentPoint.Y <= GlobalImage.LweldMat.Height)
        //        {
        //            string displalyInfo = "";
        //            if (GlobalImage.LweldMat.Channels() == 3)
        //            {
        //                byte RGB_B = GlobalImage.LweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[0];
        //                byte RGB_G = GlobalImage.LweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[1];
        //                byte RGB_R = GlobalImage.LweldMat.At<Vec3b>(currentPoint.Y, currentPoint.X)[2];
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + RGB_R.ToString() + "  G:" + RGB_G.ToString() + "  B:" + RGB_B.ToString();
        //            }
        //            else if (GlobalImage.LweldMat.Channels() == 1)
        //            {
        //                byte pixel = GlobalImage.LweldMat.At<byte>(currentPoint.Y, currentPoint.X);
        //                displalyInfo = "X:" + currentPoint.X.ToString() + "  Y;" + currentPoint.Y.ToString()
        //                    + "  R:" + pixel.ToString() + "  G:" + pixel.ToString() + "  B:" + pixel.ToString();
        //            }
        //            lbl_LweldPixel.Text = displalyInfo;
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        displalyInfo.displayInfoMain("后焊接位坐标像素信息显示异常：" + ex.Message);
        //    }
        //}

        private void btn_Home_Click(object sender, EventArgs e)
        {
            Operate_Home();
        }
        private void ClearErrorStatus()
        {
            try
            {
                GlobalVar.isEstop = false;
                for (int i = 0; i < GlobalVar.errorTips.Length; i++)
                {
                    GlobalVar.errorTips[i].haveInfo = false;
                    GlobalVar.errorTips[i].Info = string.Empty;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("清除错误状态异常："+ex.Message);
            }
        }
        private void GoHomeInMain()
        {
            Stopwatch homeSW = new Stopwatch();
            ControlSetup(false);

            GlobalVar.isAutoRun = false;
            GlobalVar.isStep = false;
            GlobalVar.isEstop = false;
            GlobalVar.isGiveUp = false;
            GlobalVar.isPause = false;
            GlobalVar.isHome = true;

            GlobalMotion.mainCard.AxisList[0].AxisStop();
            GlobalMotion.mainCard.AxisList[1].AxisStop();
            GlobalMotion.mainCard.AxisList[2].AxisStop();
            GlobalMotion.mainCard.AxisList[3].AxisStop();
            GlobalMotion.mainCard.AxisList[4].AxisStop();
            GlobalMotion.mainCard.AxisList[5].AxisStop();
            GlobalMotion.mainCard.AxisList[6].AxisStop();
            GlobalMotion.mainCard.AxisList[7].AxisStop();
            Thread.Sleep(100);
            bool homeReturn = GlobalMotion.GoHome();

            ControlSetup(true);
            GlobalVar.isHome = false;

            btn_Stop.Enabled = false;
        }
        private void ControlSetup(bool isEnable)
        {
            
            try
            {
                if (InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        pl_main.Enabled = isEnable;
                        btn_start.Enabled = isEnable;
                        btn_step.Enabled = isEnable;
                        btn_Home.Enabled = isEnable;
                        UserLogin();
   
                    }));
                }
                else
                {
                    pl_main.Enabled = isEnable;
                    btn_start.Enabled = isEnable;
                    btn_step.Enabled = isEnable;
                    btn_Home.Enabled = isEnable;

                    UserLogin();
                }
            }
            catch (System.Exception ex)
            {
                displalyInfo.displayInfoMain("控件状态设置错误："+ex.Message);
            }
            
        }

        public void DeserializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(saveFilePath, FileMode.Open))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    //GlobalVar.statisticsInfo = saveFileBF.Deserialize(fs_serial) as StatisticsNumber;
                }
            }
            catch (Exception ex)
            {
                Log4Helper.WriteLog("FormType.DeserializeFile", ex);
            }
        }
        /// <summary>
        /// 序列化 listSuckerHead listSnap listFeeder
        /// </summary>
        public void SerializeFile()
        {
            try
            {
                using (FileStream fs_serial = new FileStream(saveFilePath, FileMode.Create))
                {
                    BinaryFormatter saveFileBF = new BinaryFormatter();
                    //saveFileBF.Serialize(fs_serial, GlobalVar.statisticsInfo);
                    //GlobalVar.typedata_g = typedata;
                }
            }
            catch (Exception ex)
            {
                displalyInfo.displayInfoMain("FormMain.SerializeFile 序列化异常" + Environment.NewLine + ex.Message);
                Log4Helper.WriteLog("FormMain.SerializeFile", ex);
            }
        }

        private void btn_changeUser_Click(object sender, EventArgs e)
        {
            MessageDisplay("切换到参数配置模块");
            showHideWin((int)(winIndex.type));
            myLogin = new FormLogin();
            myLogin.TopLevel = true;
            myLogin.Show();
            GlobalVar.isChangeUser = true;
        }
    }
}
